'use strict'

//对应的是文件名不是数据库表名
let { User, Message, Comment } = require('../models');
let auth=require('../utils/auth');

let login_fn = async (ctx, next) => {
    ctx.render('login.html');
};

let talksay_fn = async (ctx, next) => {
    let username=ctx.session.username;

    //查找所有说说
    //Message与上面相对应{Message}
    let msgs = JSON.parse(JSON.stringify(await Message.findAll({
        order: [
            ["id", "desc"]
        ]
    })));

    // 查找所有的评论
    let comts = JSON.parse(JSON.stringify(await Comment.findAll()));

    let userIds = [];

    // 谁对谁说功能 第一步查找到msg中所有的fromUserId
    msgs.forEach(row => {
        userIds.push(row.fromUserId);
    });

    //谁对谁说功能 第二步查找到comts中所有的fromUserId
    comts.forEach(row => {
        userIds.push(row.fromUserId);
    });

    //谁对谁说功能 第三步查根据找查到的用户Id，查找用户表中的用户信息
    let userAll = await User.findAll({
        where: {
            id: userIds
        }
    })

    comts.forEach(row => {
        let currentUser = userAll.filter(user => {
            return row.fromUserId === user.id;
        })[0];
        row.comUserName = currentUser.username;
    });

    // 将说说和评论根据msgId按需要组合，将相应的评论挂载在对应的说说上
    msgs.forEach(msg => {
        let msgComment = comts.filter(item => {
            return item.msgId === msg.id;
        });
        let currentUser = userAll.filter(row => {
            return row.id === msg.fromUserId;
        })[0];
        msg.msgUserName = currentUser.username;
        msg.comments = msgComment;
    });

    console.log(msgs);

     let obj = {
         username: username,
         msgs: msgs
     };
    ctx.render('talksay.html',obj)
};

//注册跳转
let register_fn = async (ctx, next) => {
    ctx.render('register.html')
}

//实现登录跳转
let loginDone_fn = async (ctx, next) => {
    let usersText = ctx.request.body.usersText || '';
    let pwdText = ctx.request.body.pwdText || '';

    console.log(usersText);
    console.log(pwdText);

    let res;
    let u1 = await User.findOne({
        where: {
            username: usersText,
            password: pwdText
        }
    }).then((row) => {
        let user = JSON.stringify(row);
        let u2 = JSON.parse(user);
        if (user !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.username = row.username;
            res = { code: 200, msg: '登录成功' };
        } else {
            res = { code: 1000, msg: '账号或者密码错误请重试' };
        }
    });
    ctx.body = res;
}


//实现注册
let registerDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || '';
    let password = ctx.request.body.password || '';
    let confirmpassword = ctx.request.body.confirmpassword || '';

    if (username.length > 0 && password.length > 0 && password === confirmpassword) {
        let userDemo = await User.findOne({ where: { username: username } });
        let res = '';

        // 如果有找到同名的用户，则返回提示消息，并且不创建用户；否则创建用户，并返回提示消息
        if (userDemo) {
            // msg='当前用户名已经注册，请确认后重试';
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        } else {
            let u1 = User.create({
                username: username,
                password: password
            });
            res = { code: 200, msg: '注册成功' };
        }

        ctx.body = JSON.stringify(res);

    } else {
        console.log('用户名或密码不能为空；并且两次密码应该相同');
    }
}

//注销按钮的实现
let logout_fn = async (ctx, next) => {
    ctx.session = null;

    ctx.body = { code: 200, msg: '注销成功' };
};


//发表说说
let say_fn = async (ctx, next) => {
    let msgSay = ctx.request.body.msgSay || '';
    let userId = ctx.session.userId || '';
    let msg1 = await Message.create({
        fromUserId: userId,
        content: msgSay
    });
    let data = JSON.stringify(msg1)


    console.log(msgSay);

    ctx.body = { code: 200, data, msg: '发表成功' };
}
//评论回复
let comment_fn=async (ctx,next)=>{
    let msgId=ctx.request.body.msgId || '';
    let userId=ctx.session.userId;
    let commentText=ctx.request.body.content || '';
    let msg1=await Comment.create({
        fromUserId:userId,
        msgId:msgId,
        content:commentText
    });

    // 根据fromUsreId查询对应的用户名
    let fromUser=await User.findOne({
        where:{
            id:userId
        }
    });

    //根据msgId找到fromUserId
    let msg=await Message.findOne({
        where:{
            id:msgId
        }
    });

    //根据找到fromUserId，查找相对应的用户名
    let toUser=await User.findOne({
        where:{
            id:msg.fromUserId
        }
    });

    let data=JSON.parse(JSON.stringify(msg1));

    data.fromUserName=fromUser.username;
    data.toUserName=toUser.username;

    ctx.body={code:200,data,msg:'发表成功'};
}

module.exports = {
    '/': ['get', login_fn],
    '/register': ['get',register_fn],
    '/talksay': ['get',auth, talksay_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/say': ['post', say_fn],
    '/logout': ['post', logout_fn],
    '/comment': ['post', comment_fn]
}